//
//  ChoseAddressMapViewController.m
//  Housekeeping
//
//  Created by 刘建峰 on 16/5/27.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ChoseAddressMapViewController.h"
#import "ChoseAddressMapTableViewCell.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
static NSString * CellIndentfier = @"ChoseAddressMapTableViewCell";

@interface ChoseAddressMapViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate,MKMapViewDelegate,AMapSearchDelegate,UITextFieldDelegate>{
    
    CLLocationManager *_locationManager;
    MKMapView *_mapView;
    AMapSearchAPI *_search;
    AMapPOIAroundSearchRequest *_request;

}
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *searchField;
@property (strong, nonatomic) NSMutableArray *addressArr;
@end

@implementation ChoseAddressMapViewController

- (void)viewWillAppear:(BOOL)animated{
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _addressArr = [NSMutableArray array];
    [self initViewLayout];
    [self initGUI];
    // Do any additional setup after loading the view.
    
//    [self locationManager];
    //初始化检索对象
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIndentfier bundle:nil] forCellReuseIdentifier:CellIndentfier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
}
#pragma mark 添加地图控件
-(void)initGUI{
    _mapView=[[MKMapView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 64, 320, 190), NO)];
    [self.view addSubview:_mapView];
    //设置代理
    _mapView.delegate=self;
    
    //请求定位服务
    _locationManager=[[CLLocationManager alloc]init];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //设置地图类型
    _mapView.mapType=MKMapTypeStandard;
    
    //设置代理
    _locationManager.delegate=self;
    //设置定位精度
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    //定位频率,每隔多少米定位一次
    _locationManager.distanceFilter=10.0f;//10米定位一次
    //启动跟踪定位
    [_locationManager startUpdatingLocation];
}
- (IBAction)back:(id)sender {
    [self backBtn];
}
//加载更多数据
- (void)loadMoreData{
    _request.page = _request.page+1;
    //发起周边搜索
    [_search AMapPOIAroundSearch: _request];
}
#pragma   mark---- textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    _request.page =1;
    _request.keywords = _searchField.text;
    //发起周边搜索
    [_search AMapPOIAroundSearch: _request];
    return YES;
}

#pragma mark - 地图控件代理方法
#pragma mark 更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
//    NSLog(@"%f",userLocation.location.coordinate.latitude);
    //设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
    //    MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);
    //    MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
    //    [_mapView setRegion:region animated:true];
    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    if (!_request) {
        _request = [[AMapPOIAroundSearchRequest alloc] init];
        _request.location = [AMapGeoPoint locationWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
        _request.keywords = _searchField.text;
        // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
        // POI的类型共分为20种大类别，分别为：
        // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
        // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
        // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        _request.types = @"商务住宅|政府机构及社会团体|生活服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
        //    request.sortrule = 0;
        _request.requireExtension = YES;
        _request.page = 1;
        //发起周边搜索
        [_search AMapPOIAroundSearch: _request];
    }
    
    
    //停止跟踪定位
    [_locationManager stopUpdatingLocation];
}
#pragma mark 实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0)
    {
        return;
    }
    [_tableView.footer endRefreshing];
    if (_request.page == 1) {
        [_addressArr removeAllObjects];
    }
    for (AMapPOI *p in response.pois) {
        [_addressArr addObject:p];
    }
    [_tableView reloadData];
//    //通过 AMapPOISearchResponse 对象处理搜索结果
//    NSString *strCount = [NSString stringWithFormat:@"count: %d",response.count];
//    NSString *strSuggestion = [NSString stringWithFormat:@"Suggestion: %@", response.suggestion];
//    NSString *strPoi = @"";
//    for (AMapPOI *p in response.pois) {
//        strPoi = [NSString stringWithFormat:@"%@\nPOI: %@", strPoi, p.description];
//        NSLog(@"------------%@=====%@",p.name,p.address);
//    }
//    NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n %@", strCount, strSuggestion, strPoi];
//    NSLog(@"Place: %@", result);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 50*VerticalRatio();
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _addressArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    ChoseAddressMapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentfier];
    if (cell == nil) {
        cell= [[ChoseAddressMapTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentfier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    AMapPOI *p = _addressArr[indexPath.row];
    cell.commpanyName.text = p.name;
    cell.commpanyAdress.text = p.address;
    return cell;
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AMapPOI *p = _addressArr[indexPath.row];
    NSMutableDictionary * addressDic = [NSMutableDictionary dictionary];
    [addressDic setObject:p.province forKey:@"province"];
    [addressDic setObject:p.city forKey:@"city"];
    [addressDic setObject:p.district forKey:@"district"];
     [addressDic setObject:p.address forKey:@"address"];
    [addressDic setObject:[NSString stringWithFormat:@"%f",p.location.latitude]  forKey:@"lat"];
     [addressDic setObject:[NSString stringWithFormat:@"%f",p.location.longitude]  forKey:@"long"];
    _choseAddres(addressDic);
    [self backBtn];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
